#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <event.h>
#include <jsoncpp/json/json.h>
#include <mysql/mysql.h>
using namespace std;

enum OP_TYPE{DL = 1,ZC,CK,YD,CKYY,QX};//登陆 注册 查看 预订 查看预约 取消预约 退出

const int TCP_LISTEN_MAX = 128;
class MyLibevent; //声明



//提供监听套接字
class Socket_Ser
{
private:
    int sockfd;
    string ser_ips;
    short ser_port;
public:
    Socket_Ser()
    {
        sockfd = -1; //sockfd不在构造函数中定义
        ser_ips = "127.0.0.1";
        ser_port = 6000;
    }

    Socket_Ser(string ips,short port):ser_ips(ips),ser_port(port)
    {   
        sockfd = -1;
    }

    int Socket_Init();

    int Get_Sockfd() const
    {
        return sockfd;
    }

    ~Socket_Ser()
    {
        close(sockfd);
    }
};

//处理事件的基类
class Event_Obj  //处理描述符
{
public:
    virtual void Event_Callback() = 0;
    struct event* ev;
};

//处理监听套接字的派生类
class Event_Accept : public Event_Obj  
{
public:
    Event_Accept(int fd,MyLibevent* plib)
    {
        sockfd = fd;
        m_plib = plib;
    }
    virtual void Event_Callback();
private:
    int sockfd;
    MyLibevent* m_plib;
};

//处理连接套接字的派生类
class Event_Recv : public Event_Obj  
{
public:
    Event_Recv(int fd)
    {
        c = fd;
    }
    ~Event_Recv()
    {
        close(c);
    }
    virtual void Event_Callback();
private:
    int c;
    Json::Value val;

    void ZC_User();
    void DL_User();
    void CK_Ticket();
    void YD_Ticket();
    void CKYY_User();
    void QXYY_User();

    void Send_OK();
    void Send_ERR();
};

class MyLibevent
{
private:
    struct event_base* m_base;
public:
    MyLibevent()
    {
        m_base = NULL;
    }

    bool Libevent_Init()
    {
        m_base = event_init();
        if( m_base == NULL )
        {
            return false;
        }

        return true;
    }

    //添加一个事件
    bool Libevent_Add(int fd,Event_Obj* pObj);

    //处理事件循环 
    void Libevent_base_dispatch()
    {
        event_base_dispatch(m_base);
    }

    ~MyLibevent()
    {
        if( m_base != NULL )
        {
            event_base_free(m_base);
        }
    }
};


//封装数据库
class Mysql_Cli
{
private:
    MYSQL mysql_con;

public:
    Mysql_Cli()
    {}
    ~Mysql_Cli()
    {
        mysql_close(&mysql_con);
    }
    bool Connect_Mysql_Ser(const string user,const string passwd,const string host,
                           const string dbname,const unsigned int port);
    bool Mysql_ZC_User(string tel,string username,string userpasswd);
    bool Mysql_DL_User(string tel,string userpasswd,string& username);
    bool Mysql_CK_Ticket(Json::Value &val);
    bool Mysql_YD_Ticket(string tel,string tk_id);
    bool Mysql_CKYY_User(string tel,Json::Value &val);
    bool Mysql_QXYY_User(string yd_id);
};
